package com.groupbuying.redpacket.intercepter;

import com.groupbuying.redpacket.constants.CommonConstants;
import com.groupbuying.redpacket.constants.RedisConstans;
import com.groupbuying.redpacket.context.FilterContextHandler;
import com.groupbuying.redpacket.domain.UserToken;
import com.groupbuying.redpacket.utils.JwtUtils;
import com.groupbuying.redpacket.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthIntercepter extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(HandlerInterceptorAdapter.class);

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            String token = request.getHeader(CommonConstants.CONTEXT_TOKEN);
            UserToken userToken = JwtUtils.getInfoFromToken(token);
            FilterContextHandler.setToken(token);
            FilterContextHandler.setUsername(userToken.getUsername());
            FilterContextHandler.setName(userToken.getName());
            FilterContextHandler.setUserID(userToken.getUserId());
        }catch (Exception e){

        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String userId = FilterContextHandler.getUserID();

        //删除用户锁
        if (!StringUtils.isEmpty(userId)) {
            redisUtils.delKey(RedisConstans.USER_LOCK + userId);
        }

        FilterContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
